package com.bocloud.cmp.service.app.resource;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.dao.app.ApplicationOpenshiftClusterInfoDao;
import com.bocloud.cmp.dao.app.OpenshiftClusterDao;
import com.bocloud.cmp.entity.app.resource.ApplicationOpenshiftClusterInfo;
import com.bocloud.cmp.entity.app.resource.OpenshiftCluster;
import com.bocloud.cmp.enums.app.CommonEnum.Status;
import com.bocloud.cmp.interfaces.app.resource.AnsibleModel;
import com.bocloud.cmp.interfaces.app.resource.OpenshiftClusterService;
import com.bocloud.cmp.service.utils.RegistryUtil;
import com.bocloud.cmp.service.utils.ResourceEventPublisher;
import com.bocloud.common.enums.PostDataFormat;
import com.bocloud.common.http.HttpClient;
import com.bocloud.common.model.BsmResult;
import com.bocloud.common.model.GridBean;
import com.bocloud.common.model.Param;
import com.bocloud.common.model.Result;
import com.bocloud.common.model.SimpleBean;
import com.bocloud.common.ssh.SSH;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.GridHelper;
import com.bocloud.common.utils.ListTool;
import com.bocloud.soc.dao.intf.UserDao;
import com.bocloud.soc.entity.User;
import com.google.common.collect.Maps;

/**
 * @author Zaney
 * @data:2017年3月28日
 * @describe:openshift集群service实现类
 */
@Service("openshiftClusterService")
public class OpenshiftClusterServiceImpl implements OpenshiftClusterService {

	private static Logger logger = LoggerFactory.getLogger(OpenshiftClusterServiceImpl.class);
	private static final String OPENSHIFT_PORT = ":8443";
	private static final String HTTPS_PROXY = "https://";
	private static final String SERVER_ACOCUNT_NAME = "/api/v1/namespaces/management-infra/serviceaccounts/management-admin";
	private static final String SERVER_ACOCUNT_TOKEN = "/api/v1/namespaces/management-infra/secrets/";
	
	private final OpenshiftClusterDao openshiftClusterDao;
	private final UserDao userDao;
	private final ApplicationOpenshiftClusterInfoDao appClusterDao;
	protected final ResourceEventPublisher resourceEventPublisher;

	@Autowired
	public OpenshiftClusterServiceImpl(OpenshiftClusterDao openshiftClusterDao, UserDao userDao,
			ApplicationOpenshiftClusterInfoDao appClusterDao, ResourceEventPublisher resourceEventPublisher) {
		super();
		this.openshiftClusterDao = openshiftClusterDao;
		this.userDao = userDao;
		this.appClusterDao = appClusterDao;
		this.resourceEventPublisher = resourceEventPublisher;
	}

	@Transactional
	@Override
	public BsmResult create(Long userId, OpenshiftCluster cluster) {
		try {
			//校验集群名称
			OpenshiftCluster checkResult = openshiftClusterDao.checkName(cluster.getName());
			if (null != checkResult) {
				return new BsmResult(false, "该名称已存在");
			}
			//检测集群域名是否已经存在
			OpenshiftCluster clusterInfo = openshiftClusterDao.getOpenshiftClusterByproxyUrl(cluster.getProxyUrl());
			if (null != clusterInfo) {
				return new BsmResult(false, "该集群域名已存在");
			}
			//获取token
			String token = getToken(cluster.getProxyUrl());
			if (null == token) {
				return new BsmResult(false, "获取不到token,请检查服务连接是否正常");
			}
			
			cluster.setPassword(cluster.getPassword());
			cluster.setCreaterId(userId);
			cluster.setMenderId(userId);
			cluster.setGmtCreate(new Date());
			cluster.setGmtModify(new Date());
			cluster.setDeleted(false);
			cluster.setStatus(String.valueOf(Status.NORMAL.ordinal()));
			cluster.setToken(token);
			openshiftClusterDao.save(cluster);
			return new BsmResult(true, "创建成功!");
		} catch (Exception e) {
			logger.error("create OpenshiftCluster failure:", e);
			return new BsmResult(false, "创建失败!");
		}
	}

	@Override
	public BsmResult getTotal() {
		try {
			int count = openshiftClusterDao.count(null);
			return new BsmResult(true, count, "统计成功");
		} catch (Exception e) {
			logger.error("count OpenshiftCluster failure:", e);
			return new BsmResult(false, "统计失败!");
		}
	}

	@Override
	public BsmResult detail(Long id) {
		try {
			OpenshiftCluster cluster = this.openshiftClusterDao.query(id);
			if (null == cluster) {
				logger.info("openshift集群id = [" + id + "]不存在");
				return new BsmResult(false, "openshift集群id = [" + id + "]不存在");
			}
			// 获取用户信息
			User creator = userDao.query(cluster.getCreaterId());
			// 获取修改者信息
			User mender = userDao.query(cluster.getMenderId());
			cluster.setCreatorName(creator.getName());
			cluster.setMenderName(mender.getName());
			return new BsmResult(true, cluster, "查询详情成功");
		} catch (Exception e) {
			logger.error("Get OpenshiftCluster error：", e);
			return new BsmResult(false, null, "查询详情失败");
		}
	}
	
	@Transactional
	@Override
	public BsmResult modify(OpenshiftCluster cluster, Long userId) {
		try {
			OpenshiftCluster clusterInfo = this.openshiftClusterDao.query(cluster.getId());
			clusterInfo.setPassword(cluster.getPassword());
			clusterInfo.setName(cluster.getName());
			clusterInfo.setProxyUrl(cluster.getProxyUrl());
			clusterInfo.setMasterIp(cluster.getMasterIp());
			clusterInfo.setUsername(cluster.getUsername());
			clusterInfo.setMenderId(userId);
			clusterInfo.setRemark(cluster.getRemark());
			if (openshiftClusterDao.update(clusterInfo)) {
				return new BsmResult(true, "修改成功");
			} else {
				return new BsmResult(false, "未知错误");
			}
		} catch (Exception e) {
			logger.error("Modify openshiftCluster  fail:", e);
			return new BsmResult(false, "修改失败");
		}
	}

	@Override
	public BsmResult list(int page, int rows, List<Param> params, Map<String, String> sorter, Boolean simple) {

		List<OpenshiftCluster> clusters = null;
		List<SimpleBean> beans = null;
		int total = 0;
		GridBean gridBean = null;
		try {
			if (null == sorter) {
				sorter = Maps.newHashMap();
			}
			sorter.put("gmtCreate", Common.ONE);
			total = openshiftClusterDao.count(params);
			if (simple) {
				beans = openshiftClusterDao.list(params, sorter);
				gridBean = new GridBean(1, 1, total, beans);
			} else {
				clusters = openshiftClusterDao.list(page, rows, params, sorter);
				if (!clusters.isEmpty()) {
					for (OpenshiftCluster cluster : clusters) {
						// 获取用户信息
						User creator = userDao.query(cluster.getCreaterId());
						cluster.setCreatorName(creator.getName());
						// 获取修改者信息
						User mender = userDao.query(cluster.getMenderId());
						cluster.setMenderName(mender.getName());
					}
				}
				gridBean = GridHelper.getBean(page, rows, total, clusters);
			}
			return new BsmResult(true, gridBean, "查询成功");
		} catch (Exception e) {
			logger.error("list openshiftCluster failure:", e);
			return new BsmResult(false, "查询失败", null, null);
		}

	}

	@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
	@Override
	public BsmResult remove(List<Long> ids, Long userId) {
		try {
			if (!ids.isEmpty()) {
				// 1、删除集群时，判断该集群下有应用，不允许删除
				for (Long id : ids) {
					OpenshiftCluster cluster = openshiftClusterDao.query(id);
					List<ApplicationOpenshiftClusterInfo> appClusterInfos = appClusterDao.getAppClusterInfo(id);
					if (!ListTool.isEmpty(appClusterInfos)) {
						return new BsmResult(false, "集群[" + cluster.getName() + "]存在应用，不允许删除");
					}
					continue;
				}
				// 2、删除集群
				for (Long id : ids) {
					openshiftClusterDao.deleteById(id, userId);
				}
			}
			return new BsmResult(true, "删除成功");
		} catch (Exception e) {
			logger.error("delete openshiftCluster failure:", e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); 
			return new BsmResult(false, "删除失败");
		}
	}

	@Override
	public BsmResult listOpenshiftClusterByAppId(Long appId) {
		List<SimpleBean> beans = null;
		try {
			beans = openshiftClusterDao.listOpenshiftClusterByAppId(appId);
		} catch (Exception e) {
			logger.error("get openshiftCluster failure:", e);
			return new BsmResult(false, "按照应用获取集群异常！");
		}
		if (ListTool.isEmpty(beans)) {
			return new BsmResult(false, "按照应用获取集群异常！");
		}
		return new BsmResult(true, beans, "按照应用获取集群成功！");
	}

	@Override
	public String getToken(String proxyUrl){
		String tokenName = null;
		String url = null;
		Result message = null;
		JSONObject object = null;
		try {
			//获取 token name
			url = HTTPS_PROXY+proxyUrl+OPENSHIFT_PORT+SERVER_ACOCUNT_NAME;
			message = getMessage(url);
			if (message.isFailed()) {
				return null;
			}
			object = JSONObject.parseObject(message.getMessage());
			JSONArray secrets = JSONObject.parseArray(object.get("secrets").toString());
			for (Object secret : secrets) {
				JSONObject parseObject = JSONObject.parseObject(secret.toString());
				Object name = parseObject.get("name");
				if (name.toString().contains("token")) {
					tokenName = name.toString();
				}
			}
			//获取token 
			url = HTTPS_PROXY+proxyUrl+OPENSHIFT_PORT+SERVER_ACOCUNT_TOKEN+tokenName;
			message = getMessage(url);
			if (message.isFailed()) {
				return null;
			}
			object = JSONObject.parseObject(message.getMessage());
			JSONObject data = JSONObject.parseObject(object.getString("data").toString());
			return data.get("token").toString();
		} catch (Exception e) {
			logger.error("获取token异常", e);
			return null;
		}
	}
	/**
	 * httpClient获取数据
	 * @param url
	 * @return
	 */
	public Result getMessage(String url){
		HttpClient httpClient = new HttpClient(1000 * 10);
		httpClient.setDataFormat(PostDataFormat.RAW);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Keep-Alive", "10");
		return httpClient.get(url);
	}
	
	@Override
	public BsmResult checkMaster(OpenshiftCluster cluster){
		return RegistryUtil.checkUsernameWithPassword(cluster.getMasterIp(), cluster.getUsername(), cluster.getPassword());
	}

	@Override
	public List<OpenshiftCluster> getclusters() {
		try {
			List<OpenshiftCluster> clusters = openshiftClusterDao.selectAllCluster();
			if (ListTool.isEmpty(clusters)) {
				logger.info("没有集群");
				return null;
			}
			return clusters;
		} catch (Exception e) {
			logger.info("获取集群信息异常");
			return null;
		}
	}

	@Override
	public void updateWithField(OpenshiftCluster cluster, String[] fields) {
		try {
			openshiftClusterDao.update(cluster, fields);
		} catch (Exception e) {
			logger.error("update openshift cluster With Field error", e);
		}
	}

	@Override
	public BsmResult addNode(String newNodeType, String newNodeName, String newNodeLabel, Long clusterId) {
		BsmResult bsmResult = new BsmResult(false, "");
		String hostsFilePath = "/etc/ansible/";
		String oldHostsFileName = "hosts";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String dateTime = sdf.format(new Date());
		String bakHostsFileName = "hosts.bak."+dateTime;
		if(!StringUtils.hasText(clusterId.toString())){
			logger.error("集群信息参数异常：clusterId="+clusterId);
			bsmResult.setMessage("集群添加节点[操作失败,集群信息参数异常]");
			return bsmResult;
		}
		//节点新增完成后，检查节点是否正确
		String masterIp = "";
		String username = "";
		String password = "";
		try {
			OpenshiftCluster cluster = openshiftClusterDao.query(clusterId);
			if(null == cluster){
				logger.error("集群信息查询失败：clusterId="+clusterId);
				bsmResult.setMessage("集群添加节点[操作失败,集群信息查询结果为空]");
				return bsmResult;
			}
			masterIp = cluster.getMasterIp();
			username = cluster.getUsername();
			password = cluster.getPassword();
			AnsibleModel ansibleModel = new AnsibleModel(masterIp, username, password, newNodeName, newNodeType, newNodeLabel,hostsFilePath,oldHostsFileName,bakHostsFileName);
			// 执行ansible新增节点
			new Thread(new Runnable() {
				@Override
				public void run() {
					boolean b;
					try {
						b = ansibleTool(ansibleModel);
						if (!b) {
							logger.error("新增节点失败");
							resourceEventPublisher.send(new Result(false, "集群添加节点[操作失败]"));
						return;
						}
						bsmResult.setSuccess(true);
						resourceEventPublisher.send(new Result(true, "集群添加节点[操作成功]"));
						return;
					} catch (Exception e) {
						logger.error(e.getMessage());
						resourceEventPublisher.send(new Result(false, "集群添加节点[操作失败," + e.getMessage() + "]"));
						return;
					}
				}
			}).start();
			return new BsmResult(true, "集群添加节点[" + newNodeName + "]任务已经下发,需要的时间比较长……");
		} catch (Exception e) {
			logger.error("新增节点失败", e);
			bsmResult.setMessage("新增节点失败");
			return bsmResult;
		}
	}
	
	@Override
	public BsmResult delNode(String nodeName, Long clusterId) {
		BsmResult bsmResult = new BsmResult(false, "");
		String filePath = "/etc/ansible/hosts";
		boolean b = false;
		try {
			OpenshiftCluster cluster = openshiftClusterDao.query(clusterId);
			if(null==cluster){
				logger.error("集群信息查询失败：clusterId="+clusterId);
				bsmResult.setMessage("集群添加节点[操作失败,集群信息参数异常]");
				return bsmResult;
			}
			String masterIp = cluster.getMasterIp();
			String username = cluster.getUsername();
			String password = cluster.getPassword();
			SSH ssh = new SSH(masterIp, username, password);
			logger.error("集群删除节点[开始执行集群节点隔离]");
			//1、隔离
			if(ssh.connect()){
				b = ssh.execute("oadm manage-node "+nodeName+" --schedulable=false");
				if(!b){
					logger.error("set node ["+nodeName+"] schedulable=false fail");
					bsmResult.setMessage("集群删除节点[隔离节点["+nodeName+"]失败]");
				}
			}
			//2、撤离
			if(b&&ssh.connect()){
				String result = ssh.executeWithResult("oadm manage-node " + nodeName + "  --evacuate --force");
				if(!result.contains("0\n")){
					logger.error("set node ["+nodeName+"] evacuate fail");
				}
				logger.info("set node ["+nodeName+"] evacuate:"+result);
			}
			//3、移除节点
			if(b&&ssh.connect()){
				b = ssh.execute("oc delete node "+nodeName);
				if(!b){
					logger.error("delete node ["+nodeName+"] fail");
					bsmResult.setMessage("集群删除节点[节点撤离完成，从集群中移除节点["+nodeName+"]失败]");
				}
			}
			// 4、 备份文件
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			String stamp = format.format(new Date());
			String hostsPath = "/etc/ansible/";
			String oldFileName = "hosts";
			String newFileName = "hosts.rollback." + stamp;
			boolean file = backupFile(ssh, hostsPath, oldFileName, newFileName);
			if (!file) {
				logger.error("backup hosts file as [" + newFileName + "] fail");
				bsmResult.setMessage("备份hosts文件为[" + newFileName + "]失败]");
			}
			// 5、修改hosts备份文件，删除节点
			if (b && ssh.connect()) {
				b = ssh.execute("sed -i '/" + nodeName + "/d' " + hostsPath + newFileName);
				if(!b){
					logger.error("delete node ["+nodeName+"] from ansible/hosts file fail");
					bsmResult.setMessage("集群删除节点[节点从移除集群完成，从配置文件中移除节点["+nodeName+"]失败]");
				}
			}
			// 6、将节点卸载
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String timestamp = sdf.format(new Date());
			String uninstallFileName = filePath+".uninstall."+timestamp;
			if(b&&ssh.connect()){
				String result = ssh.executeWithResult("sed -n '/^\\[masters\\]/,/^\\[/p' " + hostsPath + newFileName
						+ " | grep -q '" + nodeName + "'");
				String command = "sed -n '/\\[OSEv3:vars\\]/,/^\\[/p' " + hostsPath + newFileName + " | sed '$d' > "
						+ uninstallFileName + ";";
				command +="echo '[OSEv3:children]' >> "+uninstallFileName+";";
				//是否是master节点
				if(result.endsWith("0\n")){
					command +="echo 'masters' >> "+uninstallFileName+";";
					command +="echo '[masters]' >> "+uninstallFileName+";";
				}else{
					command +="echo 'nodes' >> "+uninstallFileName+";";
					command +="echo '[nodes]' >> "+uninstallFileName+";";
				}
				
				command +="echo '"+nodeName+"' >> "+uninstallFileName+";";
				command +="ansible-playbook -i "+uninstallFileName+" /usr/share/ansible/openshift-ansible/playbooks/adhoc/uninstall.yml;";
				command +="rm -rf "+uninstallFileName;
				logger.info(" node ["+nodeName+"] uninstall : ansible-playbook -i "+uninstallFileName+" /usr/share/ansible/openshift-ansible/playbooks/adhoc/uninstall.yml");
				ssh.close();
				ssh.connect();
				result = ssh.executeWithResult(command);
				logger.info(" node ["+nodeName+"] uninstall over:"+result);
			}
			if(b){
				// 修改hosts文件
				boolean coverFile = coverFile(ssh, hostsPath, newFileName, oldFileName);
				if (!coverFile) {
					bsmResult.setMessage("集群删除节点[操作成功], 但修改hosts文件失败");
				}
				bsmResult.setSuccess(true);
				bsmResult.setMessage("集群删除节点[操作成功]");
			}else{
				bsmResult.setMessage("集群删除节点[操作失败]");
			}
			
		} catch (NumberFormatException e) {
			b = false;
			logger.error(e.getMessage());
			bsmResult.setMessage("集群删除节点[操作失败,"+e.getMessage()+"]");
		} catch (Exception e) {
			b = false;
			logger.error(e.getMessage());
			bsmResult.setMessage("集群删除节点[操作失败,"+e.getMessage()+"]");
		}
		return bsmResult;
	}
	
	public Boolean ansibleTool(AnsibleModel ansibleModel) throws Exception {
		// 读取服务器信息
		SSH ssh = new SSH(ansibleModel.getMasterIp(),ansibleModel.getMasterUser(),ansibleModel.getMasterPwd());
		String filePath = ansibleModel.getFilePath();
		String oldFileName = ansibleModel.getOldFileName();
		String bakFileName = ansibleModel.getBakFileName();
		//备份远程hosts文件
		boolean b = backupFile(ssh, filePath,oldFileName,bakFileName);
		if(!b){
			return false;
		}
		// 配置文件
		logger.warn("Server " + ansibleModel.getMasterIp() + " ansible File Path is :" + filePath + bakFileName);
		//在远程完成hosts配置文件拼接
		String nodeType = ansibleModel.getNodeType();
		if(null==nodeType||!("node".equals(nodeType)||"master".equals(nodeType))){
			logger.error("节点类型无法识别:nodeType="+nodeType);
			return false;
		}
		String nodeUpdate =  "";
		String nodeContent = "";
		if("node".equals(nodeType)){
			nodeContent = "new_nodes";
			nodeUpdate = "nodes";
		}
		if("master".equals(nodeType)){
			nodeContent = "new_masters";
			nodeUpdate = "masters";
		}
		String command = "sed -i '/\\[OSEv3:children\\]/a\\" + nodeContent + "' " + filePath
				+ bakFileName + ";";
		command += "echo '[" + nodeContent + "]' >> " + filePath + bakFileName + ";";
		if(StringUtils.hasText(ansibleModel.getNodeLabel().trim())){
			String[] labels = ansibleModel.getNodeLabel().split(",");
			String nodeLabels="";
			for(String label:labels){
				String[] keyValue = label.split("=");
				if(keyValue.length<2){
					continue;
				}
				String name =keyValue[0];
				String value =keyValue[1];
				nodeLabels +=",\'"+name+"\':\'"+value+"\'";
			}
			nodeLabels = nodeLabels.replaceFirst(",", "");
			command += "echo \"" + ansibleModel.getNewNodeName() + " openshift_node_labels=\\\"{" + nodeLabels
					+ "}\\\"\" >> " + filePath + bakFileName + ";";
		}else{
			command += "echo '" + ansibleModel.getNewNodeName() + "' >> " + filePath + bakFileName + ";";
		}
		//如果是master类型节点，需要新增一个new_nodes设置openshift_schuduler=false
		if("master".equals(nodeType)){
			command += "echo '[new_nodes]' >> " + filePath + bakFileName + ";";
			command += "echo '" + ansibleModel.getNewNodeName() + " openshift_schuduler=false' >> " + filePath
					+ bakFileName + ";";
		}
		if(ssh.connect()){
			b = ssh.execute(command);
			if(!b){
				logger.error("拼接ansible失败："+command);
				return false;
			}
		}
		ssh.close();
		//执行ansible新增节点
		if(ssh.connect()){
			String result = "";
			if("master".equals(nodeType)){
				result = ssh.executeWithResult(
						"ansible-playbook -i " + filePath + bakFileName
								+ " /usr/share/ansible/openshift-ansible/playbooks/byo/openshift-master/scaleup.yml",
						480000);
			}
			if("node".equals(nodeType)){
				result = ssh.executeWithResult(
						"ansible-playbook -i " + filePath + bakFileName
								+ " /usr/share/ansible/openshift-ansible/playbooks/byo/openshift-node/scaleup.yml");
			}
			logger.info(result);
		}else{
			logger.error("未执行ansible");
			return false;
		}
		ssh.close();
		//执行ansible新增节点
		if(ssh.connect()){
			String result = "";
			result = ssh.executeWithResult("oc get nodes "+ansibleModel.getNewNodeName()+"");
			ssh.close();
			int count=0;
			ssh.connect();
			while(result.contains("not found")&&count<5){
				result = ssh.executeWithResult("oc get nodes "+ansibleModel.getNewNodeName()+"");
				Thread.sleep(2000);
				count++;
			}
			if(!result.contains("not found")){
				logger.info("执行ansible成功");
			}else{
				logger.info(result);
				logger.error("执行ansible失败");
				return false;
			}
		}else{
			logger.error("未执行ansible");
			return false;
		}
		ssh.close();
		//修改hosts文件
		String labelsContent = ansibleModel.getNewNodeName();
		if(StringUtils.hasText(ansibleModel.getNodeLabel())){
			String[] labels = ansibleModel.getNodeLabel().split(",");
			String nodeLabels="";
			for(String label:labels){
				String[] keyValue = label.split("=");
				if(keyValue.length<2){
					continue;
				}
				String name =keyValue[0];
				String value =keyValue[1];
				nodeLabels +=",'"+name+"':'"+value+"'";
			}
			nodeLabels = nodeLabels.replaceFirst(",", "");
			labelsContent +=" openshift_node_labels={"+nodeLabels+"}";
		}
		command = "sed -i \"/\\[" + nodeUpdate + "\\]/a\\" + labelsContent + "\" " + filePath + oldFileName + ";";
		//如果添加master节点，需要在nodes节点下新增一条
		if("master".equals(nodeType)){
			command += "sed -i '/\\[nodes\\]/a\\" + labelsContent + "' " + filePath + oldFileName + ";";
		}
		if(ssh.connect()){
			ssh.execute(command);
		}
		ssh.close();
		// 刪除备份
		boolean deleteFile = deleteFile(ssh, filePath, bakFileName);
		if (!deleteFile) {
			logger.info("添加节点[成功]，删除备份文件失败");
		}
		return true;
	}
	
	/**
	 * 备份文件
	 * @param ssh
	 * @param filePath
	 * @param oldFileName源文件
	 * @param newFileName备份为
	 * @return
	 */
	private boolean backupFile(SSH ssh, String filePath,String oldFileName,String newFileName) {
		try {
			if (ssh.connect()) {
				String commandStr = "cd " + filePath + ";";
				commandStr += "rm -f "+newFileName+";cp "+oldFileName+" "+newFileName;
				ssh.executeWithResult(commandStr);
				logger.info("Backup file "+oldFileName+" > "+newFileName+" success");
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			logger.error("Backup file hosts.bak failed", e);
			return false;
		} finally {
			ssh.close();
		}
	}

	/**
	 * 文件覆盖
	 * 
	 * @param ssh
	 * @param filePath
	 * @param newFileName
	 * @param oldFileName
	 * @return
	 */
	private boolean coverFile(SSH ssh, String filePath, String newFileName, String oldFileName) {
		try {
			if (ssh.connect()) {
				String commandStr = "cd " + filePath + ";";
				commandStr += "mv " + newFileName + " " + oldFileName;
				ssh.executeWithResult(commandStr);
				logger.info("CoverFile file " + newFileName + " > " + oldFileName + " success");
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			logger.error("CoverFile file [" + newFileName + "]  >  [" + oldFileName + "] failed", e);
			return false;
		} finally {
			ssh.close();
		}
	}


	/**
	 * 删除备份文件
	 * @param ssh
	 * @param filePath
	 * @param newFileName
	 * @param oldFileName
	 * @return
	 */
	private boolean deleteFile(SSH ssh, String filePath, String newFileName) {
		try {
			if (ssh.connect()) {
				String commandStr = "cd " + filePath + ";";
				commandStr += "rm -f  " + newFileName;
				ssh.executeWithResult(commandStr);
				logger.info("Delete file [" + newFileName + "] success");
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			logger.error("Delete file [" + newFileName + "] failed", e);
			return false;
		} finally {
			ssh.close();
		}
	}

}
